package models

import "gorm.io/gorm"

type Product struct {
	gorm.Model
	Name        string   `json:"name" binding:"required"`
	OriginPrice float32  `json:"origin_price" binding:"required"`
	Price       float32  `json:"price" binding:"required"`
	Stock       int      `json:"stock" binding:"required"`
	CategoryID  int      `json:"category_id" binding:"required"`
	Content     string   `json:"content" binding:"required"`
	Thumb       string   `json:"thumb" binding:"required"`
	Album       string   `json:"album" binding:"required"`
	db          *gorm.DB `json:"-"`
}

func (p *Product) Delete(product_id int) error {
	result := p.db.Delete(&Product{}, product_id)
	return result.Error
}

func (p *Product) Update(entity *Product) (*Product, error) {
	result := p.db.Updates(entity)
	if result.Error != nil {
		return nil, result.Error
	}
	return entity, nil
}

func (p *Product) Create(product *Product) (*Product, error) {
	result := p.db.Create(product)
	if result.Error != nil {
		return nil, result.Error
	}
	return product, nil
}

func (Product) TableName() string {
	return "products"
}
func (p *Product) FindByID(product_id uint) (model *Product, err error) {
	model = &Product{}
	model.ID = product_id
	result := p.db.First(model)
	err = result.Error
	return
}

func (p Product) FindByCategoryID(page, rows int, category_id uint) (pages *Pages, error error) {
	var data []Product
	var all int64
	pages = &Pages{}
	query := p.db.Model(Product{}).Where("category_id = ?", category_id)
	//all
	result := query.Count(&all)
	if result.Error != nil {
		return nil, result.Error
	}
	query.Limit(rows).Offset((page - 1) * rows).Find(&data)
	result = query.Count(&all)
	if result.Error != nil {
		return nil, result.Error
	}
	return NewPages(page, rows, all, data), nil
}

type IProduct interface {
	FindByID(product_id uint) (*Product, error)
	FindByCategoryID(page, rows int, category_id uint) (pages *Pages, error error)
	Create(entity *Product) (*Product, error)
	Update(entity *Product) (*Product, error)
	Delete(product_id int) error
}

func NewProduct(db *gorm.DB) IProduct {
	return &Product{db: db}
}
